package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.SoundApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.SoundVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * @Author: Alan_Zhang
 * @Date: 2022/1/8 - 01 - 08 - 15:35
 * @Description: com.tanhua.server.service
 * @version: 1.0
 */
@Service
public class SoundService {
    @DubboReference
    private SoundApi soundApi;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate redisTemplate;


    public SoundVo reciveVoice() {

//        从mongodb里随机获取数据,一天最多10条
        Long userId = UserHolder.getUserId();

        //        使用自增长作为redis的次数值
        Long increment = redisTemplate.opsForValue().increment("Constants.Receive_Sound_KEY" + UserHolder.getUserId(), 1); //此处键key必须要用双引号
        if (increment>10){
            throw new BusinessException(ErrorResult.error());
        }
        //        时间
        Date currentTime = new Date();
//        获取当前时区的当前时间
        LocalDateTime localDateTime = LocalDateTime.ofInstant(currentTime.toInstant(), ZoneId.systemDefault());
//        获取当前时区第二天的凌晨时间
        LocalDateTime ToromorrowTime = LocalDateTime.ofInstant(currentTime.toInstant(), ZoneId.systemDefault())
                .plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0); //withNano更改纳秒值

        long seconds = ChronoUnit.SECONDS.between(localDateTime, ToromorrowTime);

        redisTemplate.opsForValue().set(Constants.Send_Sound_KEY+UserHolder.getUserId(),increment,seconds,TimeUnit.SECONDS);

        return soundApi.reciveVoice(userId,increment.intValue());

    }

    public void sendVoice(MultipartFile soundFile) throws IOException {
        if (soundFile.isEmpty()){
            throw new BusinessException(ErrorResult.error());
        }
        SoundVo soundVo = new SoundVo();
//        将语音放到FastDFS上,获取访问URL
        String filename = soundFile.getOriginalFilename();

        filename = filename.substring(filename.lastIndexOf(".") + 1);

        StorePath storePath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), filename, null);

        String soundUrl = webServer.getWebServerUrl() + storePath.getFullPath(); //获取到了语音要保存的地址
                                                        // TODO: 2022/1/9  此处要小心别忘了调全路径这个方法!!!!!
        soundVo.setSoundUrl(soundUrl);

        soundVo.setUserId(UserHolder.getUserId());
//        时间
        Date currentTime = new Date();
//        获取当前时区的当前时间
        LocalDateTime localDateTime = LocalDateTime.ofInstant(currentTime.toInstant(), ZoneId.systemDefault());
//        获取当前时区第二天的凌晨时间
        LocalDateTime ToromorrowTime = LocalDateTime.ofInstant(currentTime.toInstant(), ZoneId.systemDefault())
                                                .plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0); //withNano更改纳秒值

        long seconds = ChronoUnit.SECONDS.between(localDateTime, ToromorrowTime);

        UserInfo one = userInfoApi.findById(UserHolder.getUserId());

        BeanUtils.copyProperties(one,soundVo);

//        使用自增长作为redis的次数值
        Long increment = redisTemplate.opsForValue().increment("Send_Sound_KEY_" + UserHolder.getUserId(), 1); //此处键key必须要用双引号



        redisTemplate.opsForValue().set(Constants.Send_Sound_KEY+UserHolder.getUserId(),increment,seconds,TimeUnit.SECONDS);

        if (increment>10){

            throw new BusinessException(ErrorResult.error());
        }

        soundVo.setRemainingTimes(soundVo.getRemainingTimes()-increment.intValue());

        soundApi.sendVoice(soundVo);


    }
}
